package org.example.uhy.repository.dao;

import org.apache.ibatis.annotations.*;
import org.example.uhy.domain.model.coupon.Coupon;
import org.example.uhy.domain.model.coupon.CouponArchiveId;
import org.example.uhy.domain.model.coupon.CouponId;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 卡券数据访问对象
 */
@Mapper
public interface CouponDao {
    @Select("select count(1) as acquiredCount from mm_coupon where archive_id=#{archiveId.id} and fans_id=#{fansId}")
    Integer countOfFans(@Param("archiveId") CouponArchiveId archiveId, @Param("fansId") String fansId);

    @Select("select count(1) as acquiredCount from mm_coupon where archive_id=#{archiveId.id} and member_id=#{memberId}")
    Integer countOfMember(@Param("archiveId") CouponArchiveId archiveId, @Param("memberId") String memberId);

    @Select("select id,archive_id,name,effective_from_time as `effectiveTime.fromTime`,effective_to_time as `effectiveTime.toTime`,status,operator_id,member_id,fans_id,owner_type,source_id as `sourceId.sourceId`,source_type as `sourceId.type`,type as `parameter.type`,quota as `parameter.quota`,decrease as `parameter.decrease`,discount as `parameter.discount`,counting as `parameter.counting`,create_time,send_time,receive_time,consume_time,cancel_time,back_time from mm_coupon where id=#{id}")
    <T extends Coupon> T find(CouponId couponId);

    @Select("select id,archive_id,name,effective_from_time as `effectiveTime.fromTime`,effective_to_time as `effectiveTime.toTime`,status,operator_id,member_id,fans_id,owner_type,source_id as `sourceId.sourceId`,source_type as `sourceId.type`,type as `parameter.type`,quota as `parameter.quota`,decrease as `parameter.decrease`,discount as `parameter.discount`,counting as `parameter.counting`,create_time,send_time,receive_time,consume_time,cancel_time,back_time from mm_coupon where effective_to_time<=#{currentTime} and status<3")
    List<Coupon> allOutOfDateCoupons(LocalDateTime currentTime);

    @Insert("insert into mm_coupon(id,archive_id,name,effective_from_time,effective_to_time,status,operator_id,member_id,fans_id,owner_type,source_id,source_type,type,quota,decrease,discount,counting,create_time,send_time,receive_time) values(#{id},#{archiveId},#{name},#{effectiveTime.fromTime},#{effectiveTime.toTime},#{status},#{operatorId},#{memberId},#{fansId},#{ownerType},#{sourceId.sourceId},#{sourceId.type},#{parameter.type},#{parameter.quota},#{parameter.decrease},#{parameter.discount},#{parameter.counting},#{createTime},#{sendTime},#{receiveTime})")
    void add(Coupon coupon);

    @Update("update mm_coupon set status=#{status},member_id=#{memberId},fans_id=#{fansId},owner_type=#{ownerType},counting=#{parameter.counting},consume_time=#{consumeTime},cancel_time=#{cancelTime},back_time=#{backTime} where id=#{id}")
    void save(Coupon coupon);
}
